﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace patchPack
{
	delegate void iteratorListener(string basePath, string packFileName, string orgFilePath);
	

	class FileHandle
	{
		//打开文件夹
		public static string OpenDir()
		{
			// 选择文件夹
			FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
			DialogResult result = folderBrowserDialog.ShowDialog();
			if (result == System.Windows.Forms.DialogResult.OK)
			{
				//this.textBox1.Text = folderBrowserDialog.SelectedPath;
				//CreateEncryptDir(folderBrowserDialog.SelectedPath);

				return folderBrowserDialog.SelectedPath;

			}
			else
				MessageBox.Show("请选择文件夹");
				return "";
		}
			
		/// <summary>
		/// 
		/// </summary>
		/// <param name="basePath"></param>
		/// <param name="packFileName">文件保存的名称</param>
		/// <param name="orgFilePath">真实的路径</param>
		/// <param name="funcCallBack">函数回调</param>
		public static void ListFiles(string basePath, string packFileName, string orgFilePath, iteratorListener funcCallBack)
		{
			DirectoryInfo dirInfo = new DirectoryInfo(basePath + "\\" + orgFilePath);
			if (!dirInfo.Exists) return;
			
			FileSystemInfo[] files = dirInfo.GetFileSystemInfos();
			for (int i = 0; i < files.Length; i++)
			{
				string name1 = packFileName + files[i].Name;
				string name2 = orgFilePath + files[i].Name;

				FileInfo file = files[i] as FileInfo;

				//是文件 
				if (file != null)
				{
					////脚本文件
					//if (file.Name.EndsWith("lua"))
					//{
					//	scriptInfoTable[name1] = name2;
					//}
					//else
					//{
					//	fileInfoTable[name1] = name2;
					//};
					funcCallBack(basePath, name1, name2);
				}
				//对于子目录，进行递归调用 
				else
					name1 = name1 + ".";
					name2 = name2 + "/";
					ListFiles(basePath, name1, name2,  funcCallBack);
			}
		}

		// 获取父目录
		public static string GetParentPath(string sourDirPath)
		{
			DirectoryInfo nowDir = new DirectoryInfo(sourDirPath); // 当前目录
			string parentPath = nowDir.Parent.ToString();
			Trace.WriteLine("GetParentPath" + parentPath);
			return parentPath;
		}

		public static void CreateDir(string path)
		{
			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}
		}

		public static void CreateFile(string path)
		{
			FileStream f1 = File.Create(path);
			f1.Close();
		}

		public static void WriteFile(string path, string content)
		{
			File.WriteAllText(path, content, new UTF8Encoding());
		}

		public static string ReadFile(string path)
		{
			if (File.Exists(path))
			{
				string content =  File.ReadAllText(path);
				return content;
			};
			return "";
		}
	}
}